package com.kugong.battle;

import com.jfinal.core.Controller;
import com.kugong.match.Match;
import com.kugong.signUp.SignUp;
import com.kugong.util.CommonUtil;
import com.kugong.util.NumberUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

/**
 * Created by Administrator on 2015/8/4.
 */
public class BattleController extends Controller{

    public void index(){
        String matchId = getPara();
        Match match = Match.dao.findById(matchId);
        int playerNum = match.getInt("playerNum");
        int no = CommonUtil.roundCount(playerNum);
        List<Battle> battles = Battle.dao.qryBattleByMatchId(matchId);
        List result = new ArrayList();
        for (int k = no; k >0; k--) {
            List roundList = new ArrayList();

            for (int i = 0; i < battles.size(); i++) {
                Battle vo1 = battles.get(i);
                String groupNo = vo1.getStr("groupNo");
                if(groupNo.indexOf(k + "-")>=0) {
                    HashMap data = new HashMap();
                    data.put("vo1", vo1);
                    battles.remove(i);
                    i--;
                    for (int j = 0; j < battles.size(); j++) {
                        Battle vo2 = battles.get(j);
                        if(vo2.getStr("groupNo").equals(groupNo)){
                            data.put("vo2", vo2);
                            battles.remove(j);
                            break;
                        }
                    }
                    roundList.add(data);

                }
            }
            if(roundList.size()>0){
                result.add(roundList);
            }
        }
        setAttr("battles",result);
        setAttr("count", result.size());
        render("battle.jsp");
    }

    /**
     * 判断本轮比赛所产生的下一轮比赛是否结束，结束则不允许修改
     * 首先修改获胜标识
     * 其次删除原下轮选手，插入新选手
     */
    public void correctMistake(){
        //更新获胜者标识
        String battleId = getPara(0);
        int group = getParaToInt(1);
        int groupNo = getParaToInt(2);
        String matchId = getPara(3);
        String battleId2 = getPara(4);
        Match match = Match.dao.findById(matchId);
        if(!match.getStr("state").trim().equals("已结束")) {
            Battle winer = Battle.dao.findById(battleId);
            Battle winer2 = Battle.dao.findById(battleId2);
            int group2 = group + 1;
            int groupNo3 = groupNo / 2;
            String nextGroupNo = CommonUtil.makeGroupNo(group2, groupNo3, 3);
            Battle nextPlayer = Battle.dao.qryNext(nextGroupNo, matchId, winer2.getStr("userId"));
            if (winer != null && winer2 != null && nextPlayer != null) {
                winer.set("state", "胜利").update();
                //更新对手为失败
                winer2.set("state", "失败").set("score", 0).update();

                //删除之前的胜出选手
                nextPlayer.delete();

                //插入battle表
                Battle.dao.addBattle(winer.getStr("signName"), nextGroupNo, matchId, winer.getStr("userId"), "准备中");

                redirect("/battle/" + matchId);
            } else {
                renderText("比赛结果已经确定，无法变更。");
            }
        }else {
            renderText("比赛已结束，无法变更。");
        }
    }

    public void getVictory(){
        //更新获胜者标识
        String battleId = getPara(0);
        int group = getParaToInt(1);
        int groupNo = getParaToInt(2);
        String matchId = getPara(3);
        String battleId2 = getPara(4);
        Battle winer = Battle.dao.findById(battleId);
        Battle winer2 = Battle.dao.findById(battleId2);
        if(winer!=null&&winer2!=null) {
            if("准备中".equals(winer.getStr("state"))&&"准备中".equals(winer2.getStr("state"))){
                winer.set("state", "胜利").update();
                //更新对手为失败
                winer2.set("state", "失败").update();

                int group2 = group+1;
                int groupNo3 = groupNo/2;
                String nextGroupNo = CommonUtil.makeGroupNo(group2,groupNo3,3);
                //插入battle表
                Battle.dao.addBattle(winer.getStr("signName"), nextGroupNo, matchId, winer.getStr("userId"),"准备中");
                redirect("/battle/" + matchId);
            }else{
                renderText("该组比赛已产生结果，无需重复操作。");
            }

        }else {
            renderText("比赛信息有误，请刷新后正确操作。");
        }


    }

    public void score(){
        int id = getParaToInt("battleId");
        int score = getParaToInt("score");
        Battle vo = Battle.dao.findById(id);
        vo.set("score",score).update();
        redirect("/battle/"+vo.getStr("matchId"));
    }

    /**
     * 参数：
     * 替补战网ID
     * 比赛ID
     * 当前用户
     */
    public void backup(){
        Battle vo = getModel(Battle.class,"battle");
        String battleId = getPara("battleId");//被替补的比赛选手
        String signUpName = vo.getStr("signName");//替补选手战网
        String groupNo = vo.getStr("groupNo");//对阵组别
        String matchId = vo.getStr("matchId");//比赛编号
        //根据战网ID获取已报名该比赛的用户信息
        List<SignUp> signList = SignUp.dao.qrySignUpByNameAndMatch(signUpName,matchId);
        if(signList.size()>0){
            SignUp su = signList.get(0);
            //查询该用户是否已在本次比赛
            Battle OnlyOne = Battle.dao.qryOnlyOne(matchId,su.getStr("userId"));
            if(OnlyOne==null){
                //当前用户更新为弃权
                Battle.dao.findById(battleId).set("state","弃权").update();
                //添加替补信息
                Battle.dao.addBattle(signUpName,groupNo,matchId,su.getStr("userId"),"准备中");
                redirect("/battle/" + matchId);
            }else{
                renderText("此选手已在比赛中");
            }
        }else{
            renderText("此选手未报名本次比赛");
        }
    }
    /**
     * 参数：
     * 替补战网ID
     * 比赛ID
     * 当前用户
     */
    public void goBackUp(){
        String battleId = getPara(0);
        int group = getParaToInt(1);
        int groupNo = getParaToInt(2);
        String matchId = getPara(3);
        setAttr("battleId", battleId);
        setAttr("groupNo", CommonUtil.makeGroupNo(group,groupNo,3));
        setAttr("matchId", matchId);
        render("backUp.jsp");
    }

    /**
     * 需要添加两步：
     * 1.验证该场次已开赛,验证权限
     * 2.更新比赛状态为比赛中
     */
    public void makeBattle(){

            String matchId = getPara();
            //取出该比赛前256人 match.id match.playerNum
            Match match = Match.dao.findById(matchId);
            String state = match.getStr("state");
            int level = Integer.parseInt(getSessionAttr("level").toString().trim());
            if (level > 0) {
                if (state.trim().equals("报名中") || state.trim().equals("未开始")) {
                    match.set("state", "比赛中").update();
                    int playerNum = match.getInt("playerNum");

                    List<SignUp> list = SignUp.dao.qrySignUpForBattle(matchId, playerNum);
                    //实际人数若少于比赛规定人数的1/2则降级或取消
                    if (list.size() > playerNum / 2) {
                        //按比赛人数/2得分组数，随机取人加入分组
                        //循环2遍：获取0-比赛人数/2 随机数，取一次，人数list-1
                        for (int j = 0; j < playerNum / 2; j++) {//1
                            Random random = new Random();
                            int i = Math.abs(random.nextInt()) % (list.size());
                            SignUp vo = list.get(i);
                            String fristGroupNo = CommonUtil.makeGroupNo(1, j, 3);
                            //插入battle表
                            Battle.dao.addBattle(vo.getStr("name"), fristGroupNo, matchId, vo.getStr("userId"), "准备中");
                            list.remove(i);
                        }
                        for (int k = 0; k < playerNum / 2; k++) {
                            String fristGroupNo = CommonUtil.makeGroupNo(1, k, 3);
                            if (list.size() > 0) {
                                Random random = new Random();
                                int i = Math.abs(random.nextInt()) % (list.size());
                                SignUp vo = list.get(i);
                                //插入battle表
                                Battle.dao.addBattle(vo.getStr("name"), fristGroupNo, matchId, vo.getStr("userId"), "准备中");
                                list.remove(i);
                            } else {
                                //插入battle表
                                Battle.dao.addBattle("轮空", fristGroupNo, matchId, "", "轮空");
                            }
                        }

                        renderText("分组成功");
                    } else {
                        renderText("人数不足，请降级或取消比赛。");

                    }
                } else {
                    renderText("对阵表已经生成，无需再次生成。");
                }
            } else {
                renderText("权限不足。");
            }


    }
}
